package com.gitee.lw114514.tliasweb;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.junit.jupiter.api.Test;
import org.springframework.aop.scope.ScopedProxyUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class testJwt {
    /**
     * 测试JWT
     */
    @Test
    public void testJwt() {

        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put("username", "lw114514");
        dataMap.put("password", "123456");
        String jwt = Jwts.builder().signWith(SignatureAlgorithm.HS256, "bGlhbmd3ZWk=")
                .addClaims(dataMap) //添加自定义数据
                .setExpiration(new Date(System.currentTimeMillis() + 3600*1000))//设置过期时间为两个小时
                .compact() //构建
        ;
        System.out.println(jwt);
    }

    @Test
    public void teatParseJwt(){
        String token = "eyJhbGciOiJIUzI1NiJ9.eyJwYXNzd29yZCI6IjEyMzQ1NiIsInVzZXJuYW1lIjoibHcxMTQ1MTQiLCJleHAiOjE3NjIwOTUyMzZ9.mYzQmeTRpvE5J-TWrGlrIzFltelX57-2ABaBsPZm52I";
        Claims claims = Jwts.parser().setSigningKey("bGlhbmd3ZWk=")
                .parseClaimsJws(token)
                .getBody();
        System.out.println(claims);//如果令牌过期，则会抛出异常
    }
}
